package udp;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/*
* UDP传输数据
*
* */
public class UdpTest {

    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String str = "我是UPD方式发送的导弹";
        InetAddress ip = InetAddress.getLocalHost();
        DatagramPacket dataPacket = new DatagramPacket(str.getBytes(), 0,str.getBytes().length, ip,9999);
        socket.send(dataPacket);
        socket.close();
    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(9999);

        byte[] bytes = new byte[100];
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
        socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));

    }
}
